package com.lxs;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkDiscovery {
    public static void main(String[] args) {
        try {
            discoverNetworkResources();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public static void discoverNetworkResources() throws SocketException {
        System.out.println("=== 网络接口信息 ===");
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            if (ni.isUp() && !ni.isLoopback()) {
                System.out.println("接口: " + ni.getDisplayName());

                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    System.out.println("  IP: " + addr.getHostAddress());

                    // 尝试获取主机名
                    try {
                        String hostname = addr.getHostName();
                        if (!hostname.equals(addr.getHostAddress())) {
                            System.out.println("  主机名: " + hostname);
                        }
                    } catch (Exception e) {
                        // 忽略错误
                    }
                }
            }
        }
    }
}
